from microbit import *

ADDR = 0x39
ENABLE = 0x80
ATIME = 0x81
CONTROL = 0x8F
STATUS = 0x93
CDATAL = 0x94
CDATAH = 0x95
RDATAL = 0x96
RDATAH = 0x97
GDATAL = 0x98
GDATAH = 0x99
BDATAL = 0x9A
BDATAH = 0x9B
GCONF4 = 0xAB
AICLEAR = 0xE7

iw=i2c.write

class COLOR(object):
    def __init(self):
        iw(ADDR, bytearray([ATIME, 252]))
        iw(ADDR, bytearray([CONTROL, 0x03]))
        iw(ADDR, bytearray([ENABLE, 0x00]))
        iw(ADDR, bytearray([GCONF4, 0x00]))
        iw(ADDR, bytearray([AICLEAR, 0x00]))
        iw(ADDR, bytearray([ENABLE, 0x01]))
    def __i2cwrite_color(self, addr, reg, value):
        iw(addr, bytearray([reg, value]))

    def __ic(self, addr, reg):
        iw(addr, bytearray([reg]))
        t = i2c.read(addr, 1)
        return t[0]

    def __colormode(self):
        tmp = self.__ic(ADDR, ENABLE) | 0x2
        self.__i2cwrite_color(ADDR, ENABLE, tmp)

    def __rgbtohsl(self, color_r, color_g, color_b):
        __hue = 0
        __R = color_r * 100 / 255
        __G = color_g * 100 / 255
        __B = color_b * 100 / 255
        __maxVal = max(__R, max(__G, __B))
        __minVal = min(__R, min(__G, __B))
        __delta = __maxVal - __minVal

        if __delta <= 0:
            __hue = 0

        elif __maxVal == __R and __G >= __B:
            __hue = (60 * ((__G - __B) * 100 / __delta)) / 100

        elif __maxVal == __R and __G < __B:
            __hue = (60 * ((__G - __B) * 100 / __delta) + 360 * 100) / 100

        elif __maxVal == __G:
            __hue = (60 * ((__B - __R) * 100 / __delta) + 120 * 100) / 100

        elif __maxVal == __B:
            __hue = (60 * ((__R - __G) * 100 / __delta) + 240 * 100) / 100

        return __hue

    def get_hue(self):
        try:
            i2c.init()
            self.__init()
            self.__colormode()
            (r, g, b) = self.get_rgb()
            hue = self.__rgbtohsl(r, g, b)
            return hue
        except Exception as e:
            print('?exception' + '|cSensor error' + '~')

    def get_rgb(self):
        __tmp = self.__ic(ADDR,STATUS) & 0x1
        while not __tmp:
            sleep(1)
            __tmp = self.__ic(ADDR,STATUS) & 0x1

        c = self.__ic(ADDR, CDATAL) + \
            self.__ic(ADDR, CDATAH) * 256
        r = self.__ic(ADDR, RDATAL) + \
            self.__ic(ADDR, RDATAH) * 256
        g = self.__ic(ADDR, GDATAL) + \
            self.__ic(ADDR, GDATAH) * 256
        b = self.__ic(ADDR, BDATAL) + \
            self.__ic(ADDR, BDATAH) * 256

        avg = c / 3
        r = r * 255 / avg
        g = g * 255 / avg
        b = b * 255 / avg
        return int(r), int(g), int(b)

color = COLOR()
